<template>
  <div>
    <div class="page">
      <vxe-toolbar>
        <!--将表单放在工具栏中-->
        <template #buttons>
          <slot
            name="form"
            class="slot-form"
            :callback="{ search: search, reset: reset }"
            :query="query"
          >
            <div class="form">
              <vxe-form custom-layout :data="formData">
                <vxe-form-item
                  v-for="item in fromItem"
                  :key="item.field"
                  :title="item.title"
                  :field="item.field"
                >
                  <template #default>
                    <vxe-input
                      v-if="item.type === 'input'"
                      v-model.trim="query[item.field]"
                      type="text"
                      :placeholder="`请输入${item.title}`"
                    ></vxe-input>
                    <compSelector
                      :key="compSelectorKey"
                      v-if="item.type === 'comp-selector'"
                      :width="180"
                      v-model="query[item.field]"
                      :compType="item.compType"
                      :defaultValue="item.defaultValue?item.defaultValue:''"
                      :dictionaryType="item.dictionaryType"
                      :separateAreas="item.separateAreas"
                      :options="item.options"
                    />
                    <a-date-picker
                      v-if="item.type === 'datetime'"
                      v-model="query[item.field]"
                      :placeholder="'请选择' + item.title"
                      :format="item.format || 'YYYY-MM-DD'"
                      :show-time="{
                        defaultValue: moment('00:00:00', 'HH:mm:ss'),
                      }"
                      @change="
                        handlerPicker(
                          $event,
                          item.format || 'YYYY-MM-DD',
                          item.field
                        )
                      "
                    />
                    <ych-multi-select-tag
                      style="width: 200px"
                      v-if="item.type === 'ych-select-tag'"
                      v-model="query[item.field]"
                      :type="'select'"
                      :dictCode="item.dictType"
                      :disabled="item.disabled || false"
                    />
                  </template>
                </vxe-form-item>
                <vxe-form-item>
                  <template>
                    <vxe-button
                      type="submit"
                      status="primary"
                      content="查询"
                      @click="search"
                      icon="vxe-icon-search"
                      :class-name="toobar.class"
                    ></vxe-button>
                    <vxe-button
                      type="reset"
                      content="重置"
                      icon="vxe-icon-repeat"
                      @click="reset"
                    ></vxe-button>
                  </template>
                </vxe-form-item>
              </vxe-form>
            </div>
          </slot>

          <div class="toobar">
            <slot name="button" :query="query">
              <vxe-button
                v-if="toobar.add"
                type="submit"
                status="primary"
                :content="toobar.content || '添加'"
                @click="handlerAdd"
                :class-name="toobar.class || ''"
              ></vxe-button>
            </slot>
            <slot name="update" :refresh="getQueryList"></slot>
            <!-- <Renders :row="toobar"></Renders> -->
          </div>
        </template>
      </vxe-toolbar>
      <vxe-table
        border
        ref="xGrid"
        :height="clientHeight"
        @checkbox-change="checkboxChange"
        @checkbox-all="checkboxAll"
        :id="rowId"
        align="center"
        :custom-config="
          customConfig || {
            storage: true,
            visible: true,
            checkMethod: this.checkColumnMethod,
          }
        "
        resizable
        @resizable-change="resizableChangeEvent"
      >
        <!-- resizable 表格可拖动 -->
        <!--  // visible 是否显示字段按钮
      // resizable：启用列宽状态
      // checkMethod 自定义列是否允许列选中的方法，该方法的返回值用来决定这一列的 checkbox 是否可以选中 -->
        <vxe-column
          v-for="config in columns"
          :key="config.field"
          :type="config.type"
          :field="config.field"
          :title="config.title"
          :fixed="config.fixed"
          :width="config.width"
          :filters="config.filters"
        >
          <template
            v-if="config.field !== 'operate' && config.type !== 'seq'"
            #default="{ row }"
          >
            <slot :name="config.fixed" :callback="checkView" :row="row">
              {{ row[config.field] }}
            </slot>
          </template>
          <template
            v-else-if="config.field == 'operate' && config.type !== 'seq'"
            #default="{ row }"
          >
            <slot name="operate" :callback="checkView" :row="row">
              <!-- //存在 -->
              <div v-if="table.operate.flag">
                <!-- <com
                  :render="config.render"
                  :template="table.operate.template"
                  :html="table.operate.html"
                  :row="row"
                ></com> -->
                <vxe-button
                  title="编辑"
                  status="primary"
                  content="编辑"
                  @click="handlerEdit(row)"
                ></vxe-button>
                <vxe-button
                  :title="'删除'"
                  status="danger"
                  :content="'删除'"
                  @click="handlerDelete(row)"
                ></vxe-button>
              </div>
              <!-- 当 template 不存在 -->
              <vxe-button
                v-else
                :title="config.content || '办理'"
                status="primary"
                :content="config.content || '办理'"
                @click="checkView(row)"
              ></vxe-button>
            </slot>
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-pager
        :current-page="pager.currentPage"
        :page-size="pager.pageSize"
        :total="pager.total"
        :layouts="pager.layouts"
        @page-change="handlePageChange"
      >
      </vxe-pager>
    </div>
    <vxe-modal
      v-model="vxModalAdd.visabled"
      :width="vxModalAdd.width"
      :height="vxModalAdd.height"
      :title="vxModalAdd.title"
      :destroy-on-close="true"
      show-footer
    >
      <template #default>
        <slot name="addmodal">
          <everday-form
            :formItem="toobar.formItem"
            :beforeCreate="beforeCreateForm"
            :labelcol="toobar.labelcol"
          >
          </everday-form>
        </slot>
      </template>

      <template #footer>
        <div>
          <slot name="footer">
            <vxe-button
              type="submit"
              status="primary"
              content="提交"
              @click="addOk"
            ></vxe-button>

            <vxe-button
              type="submit"
              status="primary"
              content="取消"
              @click="addClear"
            ></vxe-button>
          </slot>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
import everdayForm from "@/views/everydayCheck/components/everday-form";
import moment from "moment";
import compSelector from '@/components/compSelector/compSelector'
import Vue from "vue";
import Renders from "../renders.vue";
import YchMultiSelectTag from "@/components/dict/YchMultiSelectTag";
export default {
  name: "com-vxe-table",
  components: {
    everdayForm,
    YchMultiSelectTag,
    compSelector,
    com: {
      props: {
        template: Object,
        html: String,
        row: Object,
        render: {
          type: Function,
          required: true,
        },
      },
      render(h, ctx) {
        const arr = [];
        const params = {
          row: ctx.props.row,
          index: ctx.props.row["id"],
        };
        const VNode = ctx.props.render(h, params); //parmas 可以把参数传回给二中的tableColumns使用，
        arr.push(VNode);
        return h("div", arr, "");
      },
    },
    Renders,
  },
  props: {
    // 表格字段跟配置
    columns: {
      type: Array,
      default() {
        return [];
      },
    },
    // 请求页码的数据代理接口
    axios: {
      type: Function,
    },
    // 显示表单数组
    fromItem: {
      type: Array,
      default() {
        return [];
      },
    },
    // 表单对象
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
    // 穿过来的参数
    initialize: {
      type: Object,
      default() {
        return {};
      },
    },
    // id
    rowId: {
      type: String,
      default() {
        return "id";
      },
    },
    // 显示字段配置对象
    customConfig: {
      type: Object,
      // visible 是否显示字段按钮
      // resizable：启用列宽状态
      // checkMethod 自定义列是否允许列选中的方法，该方法的返回值用来决定这一列的 checkbox 是否可以选中
    },
    height: {
      type: String,
      default: "",
    },
    config: {
      type: Object,
      default() {
        return {};
      },
    },
    // 判断当前谁在操作这个组件
    vId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      compSelectorKey:null,
      clientHeight: 400,
      // 表单
      query: this.formData,
      // 配置项
      // id
      selectKeysId: [],
      selectKeysRow: [],
      tableData: [],
      pager: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        layouts: [
          "PrevPage",
          "JumpNumber",
          "NextPage",
          "FullJump",
          "Sizes",
          "Total",
        ],
      },

      // 表格配置对象
      toobar: {
        //  添加按钮
        add: false,
        class: "",
        modal: false,
        labelcol: { span: 8 },
        modalConfig: {
          visabled: false,
          width: "60vw",
          height: "70vh",
          title: "",
          content: "",
        },
        formItem: [],
        form: null,
        axios: {
          add: null,
        },
      },
      vxModalAdd: {
        visabled: false,
        width: "65vw",
        height: "70vh",
        title: "",
        content: "",
      },

      // 表格配置项
      table: {
        operate: {
          flag: false,
          template: "",
          html: "",
        },
      },
    };
  },
  watch: {
    config: {
      immediate: true,
      deep: true,
      handler() {
        if (this.config instanceof Object) {
          const { toobar, table } = this.config;
          if (toobar) {
            this.toobar = { ...this.toolbar, ...toobar };
          }
          if (table) {
            this.table = { ...this.table, ...table };
          }
        }
      },
    },
    toobar: {
      deep: true,
      handler() {
        if (this.toobar.modal) {
          const { modalConfig } = this.toobar.modalConfig;
          this.vxModalAdd = { ...this.vxModalAdd, modalConfig };
        }
      },
    },
    height:{
     immediate:true,
     deep:true,
     handler() {
      if(this.height) {
        this.clientHeight = this.height
      }
     }
    }
  },
  created() {
    this.$nextTick(() => {
      let height = document.querySelector(".main").clientHeight;
      this.clientHeight = height - 160;
    });
  },
  mounted() {
    this.getQueryList();
  },
  methods: {
    moment,
    // 对象
    getQuery(value2 = {}) {
      const fromData = Object.assign(this.query, value2);
      // fromData.pageNo = this.pager.currentPage;
      // fromData.pageSize = this.pager.pageSize;
      return fromData;
    },
    // 请求数据列表
    getQueryList(timeout) {
      //console.log(this.getQuery(this.initialize),this.pager)
      if (timeout) clearTimeout(timeout);
      const fromData = this.getQuery(this.initialize);
      this.axios({...fromData,pageNo:this.pager.currentPage,pageSize:this.pager.pageSize}).then((res) => {
        if (res.success) {
          const { result } = res;
          if (result instanceof Array) {
            this.tableData = result;
          } else {
            this.tableData = result.records;
            this.pager.currentPage = result.current;
            this.pager.pageSize = result.size;
            this.pager.total = result.total;
          }
          this.$refs.xGrid.reloadData([]);
          timeout = setTimeout(() => {
            this.$refs.xGrid.loadData(this.tableData);
            if (timeout) clearTimeout(timeout);
          }, 0);
        } else {
          //console.log(this.tableData, "error");
          this.$message.error(res.message);
        }
      });
    },
    // 搜索
    search(from = {}) {
      this.getQueryList();
    },
    // 重置
    reset() {
      this.query = {};
      this.getQueryList();
      this.compSelectorKey = Date.now()
    },
    // 表格-查看
    checkView(row) {
      this.$emit("check-view", row);
    },
    // 再次调用函数或者接口
    callback(fn) {
      if (typeof fn === "function") {
        fn();
      }
    },
    // 勾选-单个
    checkboxChange(val) {
      //console.log(val, "单个");
      // if (checked) {
      //   this.selectKeysId.push(row[this.rowId]);
      // } else {
      //   this.selectKeysId.filter((s) => s !== row[this.rowId]);
      // }
      
      if(val.records.length){
        val.records.forEach(item => {
          if(this.selectKeysId.indexOf(item[this.rowId]) == -1){
            this.selectKeysId.push(item[this.rowId])
          }
        });
      }else{
        this.selectKeysId = []
      }
      this.$emit('checkboxChange',this.selectKeysId,val.records)
    },
    // 勾选-多个
    checkboxAll(val) {
      if(val.records.length){
        val.records.forEach(item => {
          if(this.selectKeysId.indexOf(item[this.rowId]) == -1){
            this.selectKeysId.push(item[this.rowId])
          }
          
        });
      }else{
        this.selectKeysId = []
      }
      this.$emit('checkboxChange',this.selectKeysId,val.records)
    },
    // 分页
    handlePageChange(page) {
      //console.log(page, "page");
      this.pager = { ...this.pager, ...page };
      //console.log(this.pager)
      this.getQueryList();
    },
    // 表格列 拖动
    resizableChangeEvent(object) {
      //console.log(object);
    },
    // 数据代理-编辑
    handlerEdit(row) {
      this.$emit("com-edit", this.vId, row);
      //console.log(row, "handlerEdit", this.vId);
    },
    // 数据代理-删除
    handlerDelete(row) {
      this.$emit("com-delete", this.vId, row, this.getQueryList);
    },
    // 数据代理-添加
    handlerAdd() {
      this.$emit("add-open", this.toobar, this.vId);
      this.vxModalAdd.visabled = true;
    },
    // 添加-确定
    addOk() {
      const { axios } = this.toobar;
      if(axios){
        if (axios.add instanceof Function) {
          this.axios(this.toobar, this.toobar.form, this.vId, this.getQueryList);
        }
      }
      
      this.$emit(
        "vadd-ok",
        this.toobar,
        this.toobar.form,
        this.vId,
        this.getQueryList
      );
      this.vxModalAdd.visabled = false;
    },
    addClear() {
      this.$emit("add-clear", this.toobar, this.toobar.form, this.vId);
    },
    // 添加form表单对象
    beforeCreateForm(form) {
      this.toobar.form = form;
    },
    // 自定义列是否允许列选中的方法，该方法的返回值用来决定这一列的 checkbox 是否可以选中
    checkColumnMethod() {},
    //表单-时间触发
    handlerPicker(event, format, prototype) {
      if (event) {
        this.query[prototype] = moment(event).format(format);
      } else {
        this.query[prototype] = "";
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../assets/common.less");
.page {
  box-sizing: border-box;
  background: #fff;
  padding: 20px;
}
.slot-form {
}
.toobar {
}
::v-deep .vxe-buttons--wrapper {
  display: flex;
  justify-content: space-between;
}
</style>
